<?php

namespace zhtfrontend\controllers;

use common\components\extenders\AjaxObject;
use common\components\extenders\RequestManage;
use common\components\services\customer\Createcard;
use common\models\datas\Admin;
use common\components\helpers\Fun;
use common\models\datas\Customer;
use doumiaoduo\buildform\BuildForm;
use zhtfrontend\models\datas\Arrangement;
use zhtfrontend\models\datas\ClassLesson;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\Classroom;
use zhtfrontend\models\datas\ClassroomAttr;
use zhtfrontend\models\datas\ClassStudent;
use zhtfrontend\models\datas\Course;
use zhtfrontend\models\datas\Mechanic;
use common\models\datas\Student;
use zhtfrontend\models\datas\Teacher;
use zhtfrontend\models\datas\StudentCheck;
use zhtfrontend\models\datas\LessonStudent;
use zhtfrontend\models\datas\SubstituteCheck;
use yii\data\Pagination;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use yii\web\BadRequestHttpException;
use yii\web\Response;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use common\models\datas\Site;

class OldclassmanageController extends \zhtfrontend\components\bases\BaseController
{

    /**
     * 首页
     */
    public function actionIndex()
    {

        $search_data = \Yii::$app->request->get();
//        print_r($search_data);die;

        $class_manage = ClassManage::find()->where(['is_old'=>1])->indexBy('class_id')->orderBy('class_id DESC ');
        if (!empty($search_data['course'])) {
            $course_id = Course::find()->select('id')->where(['like', 'name', $search_data['course']])->column();
            $arrange_id1 = Arrangement::find()->select('id')->where(['in', 'course_id', $course_id])->column();
            $class_manage->andWhere(['in', 'associate_id', $arrange_id1]);
        }
        if (!empty($search_data['teacher'])) {
            $teacher_id = Teacher::find()->select('id')->where(['like', 'name', $search_data['teacher']])->column();
            $arrange_id2 = Arrangement::find()->select('id')->where(['in', 'teacher_id', $teacher_id])->column();
            $class_manage->andWhere(['in', 'associate_id', $arrange_id2]);
        }
        if (!empty($search_data['classroom'])) {
            $classroom_id = Classroom::find()->select('id')->where(['like', 'name', $search_data['classroom']])->column();
            $arrange_id3 = Arrangement::find()->select('id')->where(['in', 'classroom_id', $classroom_id])->column();
            $class_manage->andWhere(['in', 'associate_id', $arrange_id3]);
        }
        if (!empty($search_data['mechanic'])) {
            $mechanic_ids = Mechanic::find()->select('id')->where(['like','name',$search_data['mechanic']])->column();
            $class_manage->andWhere(['in', 'mechanic_id', $mechanic_ids]);
        }
        if (isset($search_data['status']) && $search_data['status'] != null) {
            $class_manage->andWhere(['status'=>$search_data['status']]);
        }
        if (!empty($search_data['start_time'])) {
            $start_time = str_replace(':','',$search_data['start_time']);
            $classroom_attr = ClassroomAttr::find()->select('id')->where(['start_time' => (int)$start_time])->column();
            $arrange_list = Arrangement::find()->where(['is_delete'=>0,'is_online'=>0])->all();
            $arrange_id4 = [];
            foreach($arrange_list as $arr){
                   if($arr->classroom_attr_id){
                      $new_arr =  explode(',',$arr->classroom_attr_id);
                       foreach($new_arr as $v){
                           if(in_array($v,$classroom_attr))
                               $arrange_id4[] = $arr->id;
                       }
                   }
            }
            $class_manage->andWhere(['in', 'associate_id', $arrange_id4]);
        }
        if (!empty($search_data['opentime'])) {
            $day = floor(\Yii::$app->formatter->asTimestamp($search_data['opentime']) / (60 * 60 * 24));
            $min = $day * 60 * 60 * 24;
            $max = ($day + 1) * 60 * 60 * 24;
            $class_manage->andWhere(['between', 'start_time', $min, $max]);
        }
        $openClassModel = ClassManage::find()->where(['status'=>1,'is_old'=>1]);
        $mids = Fun::getMechanicIds();
        if($mids){
            $class_manage->andWhere(['mechanic_id'=>$mids]);
            $openClassModel->andWhere(['mechanic_id'=>$mids]);
        }
        if(isset(\Yii::$app->user->identity)&&\Yii::$app->user->identity->role == 'business_director') {
            $ids = Mechanic::find()->select('id')->where(['admin_id'=>\Yii::$app->user->id])->column();
            $class_manage->andWhere(['mechanic_id'=>$ids]);
            $openClassModel->andWhere(['mechanic_id'=>$ids]);
        }
        //老师看属于自己的班级、班主任查看自己的班级
        $role = isset(\Yii::$app->user->identity)?\Yii::$app->user->identity->role:'';
        if($role == 'teache_teacher'){
            $arrangement_id4=Arrangement::find()->select('id')->where(['teacher_id'=>\Yii::$app->user->identity->teacher_id])->column();
            $class_manage->andWhere(['in','associate_id',$arrangement_id4]);
        }elseif($role == 'class_teacher'){
            $class_manage->andwhere(['headmaster'=>\Yii::$app->user->identity->id]);
        }
        $pages = new Pagination(['totalCount' =>$class_manage->count(), 'pageSize' =>10,'params'=>array_merge($_GET,$search_data)]);
        $class_manage = $class_manage->offset($pages->offset)->limit($pages->limit)->all();
        $class_count = [];
        $openClass = $openClassModel->all();
        if ($class_manage != null) {
            foreach ($class_manage as $k => $v) {
                if (isset($v->arrangeMent)) {
                    $count = ClassStudent::find()->where(['class_manage_id' => $k])->count();
                    $class_count[$k]['id'] = $k;
                    $class_count[$k]['code'] = $v->code;
                    $class_count[$k]['status'] = $v->status;
                    $class_count[$k]['start_time'] = $v->start_time;
                    $class_count[$k]['end_time'] = $v->end_time;
                    $class_count[$k]['avatar'] = 'images/images/noperson.png';
                    $class_count[$k]['course_name'] = isset($v->arrangeMent->course)?$v->arrangeMent->course->name:'';
                    $class_count[$k]['teacher_name'] = isset($v->arrangeMent->teacher)?$v->arrangeMent->teacher->name:'';
                    $class_count[$k]['classroom_name'] = isset($v->arrangeMent->classroom)?$v->arrangeMent->classroom->name:'';
                    $class_count[$k]['mechanic_name'] = isset($v->mechanic)?$v->mechanic->name:'';
                    $str = '';
                    $classrooomattr = [];
                    if(!empty($v->arrangeMent->classroom_attr_id)){
                        $classroom_attr_ids = explode(',',$v->arrangeMent->classroom_attr_id);
                        $classrooomattr = ClassroomAttr::find()->where(['id'=>$classroom_attr_ids])->asArray()->all();
                        foreach($classrooomattr as $key1=>$c){
                             $str .= Fun::getClassTime($c['start_time'],$c['end_time'],$c['classday']).' ';
                            $classrooomattr[$key1]['teacher'] = $class_count[$k]['teacher_name'];
                        }
                    }
                    $class_count[$k]['class_time'] = $str;
                    $class_count[$k]['max_number'] =  isset($v->arrangeMent->max_number)?$v->arrangeMent->max_number:'';
                    $class_count[$k]['opening_number'] = isset($v->arrangeMent->max_number)?$v->arrangeMent->opening_number:'';
                    $class_count[$k]['COUNT(id)'] = $count;
                    $class_count[$k]['is_open'] = 1; //可以开班
                    $class_count[$k]['end_time'] = $v->end_time;
                   if($openClass) {
                       foreach ($openClass as $open) {
                           if ($v->status == 1) break;
                           if ($open->arrangeMent && !empty($open->arrangeMent->classroom_attr_id)) {
                                $e = explode(',',$open->arrangeMent->classroom_attr_id);
                               $teacher = !empty($open->arrangeMent->teacher)?$open->arrangeMent->teacher->name:'';
                                $opencrr = ClassroomAttr::find()->where(['id'=>$e])->asArray()->all();
                               foreach($opencrr as $o){
                                   foreach($classrooomattr as $c){
                                        if($teacher == $c['teacher'] && $o['classday'] == $c['classday'] && $o['start_time'] == $c['start_time'])
                                            $class_count[$k]['is_open'] = 0; //不可以开班
                                   }
                               }
                           }
                       }
                   }
                }
            }
        }
        return $this->render('index', ['data' => $class_count,'pages'=>$pages]);
    }

    /**
     * 课时详情
     */
    public function actionLesson()
    {
        $this->layout='@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $class_lesson = ClassLesson::findAll(['class_id' => \Yii::$app->request->get('id')]);
        return $this->render('lesson', ['details' => $class_lesson]);
    }

    /**
     * 学员列表->打卡
     */
    public function actionDetails()
    {
        $this->layout='@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $class_manage = ClassManage::findOne([\Yii::$app->request->get('id')]);
        if ($class_manage === null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $student_list = ClassStudent::find()->where(['class_manage_id' => $class_manage->class_id])->all();
        return $this->render('details', ['details' => $student_list, 'class_id' => \Yii::$app->request->get('id')]);
    }

    /**
     * 打卡列表
     */
    public function actionSign()
    {
        $this->layout='@app/views/layouts/iframe.php';
        $student_id = \Yii::$app->request->get('id');
        $class_manager_id = \Yii::$app->request->get('class_id');
        if ($student_id == null || $class_manager_id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $clma = ClassManage::findOne($class_manager_id);
        $cs = ClassStudent::find()->where(['class_manage_id'=>$class_manager_id,'student_id'=>$student_id])->one();
        $student = (new Query())->select('*')->from('{{%student}}')->where(['id' => $student_id])->one(Fun::getSysDb());
        $list = StudentCheck::find()->where(['student_id'=>$student_id,'class_student_id'=>$cs->id])->all();
        $class_lesson = [];
        $i = 0;
        $arrang = Arrangement::findOne($clma->associate_id);
        foreach($list as $v){
            $cl = ClassLesson::findOne($v->class_lesson_id);
            $class_lesson[$i]['title'] = isset($arrang->course)?$arrang->course->name:'';
            $class_lesson[$i]['name'] = isset($v->student)?$v->student->name:'';
            $class_lesson[$i]['class_date'] = \Yii::$app->formatter->asDate($cl->class_date);
            $class_lesson[$i]['time'] = Fun::getClassTime($cl->start_time,$cl->end_time);
            $class_lesson[$i]['lesson'] =$cl->lesson;
            $class_lesson[$i]['status'] = (int)$v->status;
            $class_lesson[$i]['lesson_id'] = $cl->class_id;
            $class_lesson[$i]['student_id'] = $v->student_id;
            $class_lesson[$i]['class_id'] = $cs->class_manage_id;
            $class_lesson[$i]['id'] = $v->id;
            $i++;
        }



        return $this->render('sign', ['details' => $class_lesson, 'student' => $student]);
    }

    /**
     * 保存打卡
     */
    public function actionSignin()
    {
        $id = \Yii::$app->request->get('id');
        $class_id = \Yii::$app->request->get('class_id');
        $student_id = \Yii::$app->request->get('student_id');
        $student_check = StudentCheck::findone($id);
        $LessonModel = ClassLesson::findOne($student_check->class_lesson_id);

//        $start_time = $LessonModel->class_date;
//        $start_second = (int)substr($LessonModel->start_time, 2);
//        $end_second = (int)substr($LessonModel->end_time, 2);
//        if(strlen($LessonModel->start_time) == 3){
//            $start_second = (int)substr($LessonModel->start_time, 1);
//        }
//        if(strlen($LessonModel->end_time) == 3){
//            $end_second = (int)substr($LessonModel->end_time, 1);
//        }
//        $class_length = (floor($LessonModel->end_time / 100) - floor($LessonModel->start_time / 100)) * 60 + ($end_second-$start_second);
//        $end_time = $LessonModel->class_date+$class_length*60+7200;
//        if((time() > $start_time-7200) || (time() > $end_time)){
//            $return = ['status' => 2];
//            return json_encode($return);
//        }
        if($LessonModel->status == 0){
            $LessonModel->status =1;
            $LessonModel->save(false);
        }
        $classManager = ClassManage::findOne($class_id);
        $Student = (new Query())->from('{{%student}}')->where(['id' => $student_id])->one(Fun::getSysDb());

            //插入记录表--记录上课
            $lessstudent = LessonStudent::find()->where(['lesson_id' => $LessonModel->lesson_id, 'student_id' => $student_id])->one();
            $lessstudent->status = 1;
            $lessstudent->save(false);
            if ($lessstudent->id) {
                //找到相应记录直接改状态
                $student_check->status = 1;
                $student_check->created_at = time();
                if ($student_check->save(false)) {
                    //插入代打卡表---插入代打卡表
                    $student = (new Query())->select('*')->from('{{%student}}')->where(['id' => $student_id])->one(Fun::getSysDb());
                    $SubstituteCheckModel = new SubstituteCheck();
                    $SubstituteCheckModel->userid = \yii::$app->user->id;
                    $SubstituteCheckModel->student_id = $student_id;
                    $SubstituteCheckModel->customer_id = $student['customer_id'];
                    $SubstituteCheckModel->created_at = time();
                    $SubstituteCheckModel->save();
                    if ($SubstituteCheckModel->id) {
                        $str = '';
                        $str .= ' <table>
                                 <tr><td colspan="2" align="center">打卡</td></tr>
                                 <tr><td>姓名:</td><td>' . Html::encode($Student['name']) . '</td></tr>
                                 <tr><td>上课日期:</td><td>' . Html::encode(\Yii::$app->formatter->asDate($LessonModel->class_date)) . '</td></tr>
                                 <tr><td>课程:</td><td>' . Html::encode($LessonModel->title) . '</td></tr>
                                 <tr><td>老师:</td><td>' . Html::encode($classManager->arrangeMent->teacher->name) . '</td></tr>
                                 <tr><td>教室:</td><td>' . Html::encode($classManager->arrangeMent->classroom->name) . '</td></tr>
                                 <tr><td>开票时间:</td><td>' . date('Y-m-d') . '</td></tr>
                             </table>';
                        $return = ['status' => 1, 'str' => $str];
                        return json_encode($return);
                    }
                }
            }else {
                $return = ['status' => 0];
                return json_encode($return);
            }
    }

    /**
     * 开班
     */
    public function actionOpen()
    {
        $this->layout='@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $id = \Yii::$app->request->get('id');
        $model = ClassManage::findOne([$id]);
        $model->scenario = 'open_old';
        if ($model === null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $studentCount = ClassStudent::find()->where(['class_manage_id'=>$id])->count();
        if($studentCount == 0){
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '没有学生暂时不能开班！'));
        }
        $arrangement = Arrangement::findOne([$model->associate_id]);
        if ($arrangement === null || empty($arrangement->classroom_attr_id)) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $max_number=!empty($arrangement)?$arrangement->max_number:'';
        $classroom_attr_ids = explode(',',$arrangement->classroom_attr_id);
        $goods_time_array = ClassroomAttr::find()->where(['id'=>$classroom_attr_ids])->orderBy('classday,start_time ASC')->asArray()->all(Fun::getSiteDb());
        if ($goods_time_array === null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        if (\Yii::$app->request->isAjax) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $student = ClassStudent::find()->where(['class_manage_id' => $model->class_id, 'status' => 0])->orderBy('id asc')->all();
            $ajax_object = new AjaxObject();
            $ajax_object->data = count($student) > 0 ? Fun::asArray($student, ['student_name', 'price', 'age', 'tel', 'card_id']) : [];
            return $ajax_object;
        }
        $count = (int)$arrangement->class_count;
        $form = new BuildForm('@app/components/forms/classmanageForm.php');
        $form->loadModel(['classmanage' => $model]);
        $site = Site::findOne(['id'=>Fun::getSiteId()]);
        //班主任
        $site = Site::findOne(['id'=>Fun::getSiteId()]);
        if($site->mode == 'A'){
            if(isset(\Yii::$app->user->identity)&&in_array(\Yii::$app->user->identity->role,['mechanic_leader','mechanic'])) {
                $mechanic_ids = Fun::getMechanicIds();
                $admin = Admin::find()->where(['role' => 'class_teacher'])->andwhere(['in','mechanic_id',$mechanic_ids])->asArray()->all(Fun::getSiteDb());
            }elseif(isset(\Yii::$app->user->identity)&&\Yii::$app->user->identity->role == 'admin'){
                $admin = Admin::find()->where(['role' => 'class_teacher'])->asArray()->all(Fun::getSiteDb());
            }else{
                $admin = [];
            }
        }else{
            $admin = Admin::find()->where(['role' => 'class_teacher'])->asArray()->all(Fun::getSiteDb());
        }
        $form->setItems('classmanage', 'headmaster', ArrayHelper::map($admin, 'id', 'name'));
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {

            $transaction = \Yii::$app->db->beginTransaction();
            try {
                if ($model->status == 1) {
                    $start_time=0;
                    $end_time=0;
                    $diff=0;
                    $times_week = count($goods_time_array); //每周上课次数
                    //插入class_lesson
                    $startweek = (int)date("N", \Yii::$app->formatter->asTimestamp($model->start_time));
                    $j=1;
                    $first_week_times=0;
                    $insert_array=[];
                    $length=$flag=$count+$times_week;
                    $array=$this->getClassLessonArray($length,$goods_time_array);
                    $index=0;
                    for($m=0;$m<$length;$m++){
                        if($m==0){//第一周
                            foreach($goods_time_array as $k=>$v){
                                if($startweek>$v['classday'] ){
                                    unset($array[$k]);
                                    $flag--;
                                    $index++;
                                }
                                else{
                                    $s = (int)$array[$index+$diff]['start_time'];
                                    if($j==1){
                                        $start_time= strtotime($model->start_time) + floor($s/100) * 60 * 60+(int)(substr($s,2))*60; //开始上课时间
                                    }
                                    $insert_array[$j]['class_id'] = $id;
                                    $insert_array[$j]['class_date'] = strtotime($model->start_time) + ($array[$index+$diff]['classday']-$startweek) * 60 * 60 * 24+ floor($s/100) * 60 * 60+(int)(substr($s,2))*60;
                                    $insert_array[$j]['start_time'] = $array[$index+$diff]['start_time'];
                                    $insert_array[$j]['end_time'] = $array[$index+$diff]['end_time'];
                                    $insert_array[$j]['lesson'] = $j;
                                    $insert_array[$j]['title'] = isset($arrangement->course->name) ? $arrangement->course->name : '';
                                    $insert_array[$j]['status'] = 0;
                                    $insert_array[$j]['ovo'] = isset($arrangement->course->teacher_form) ? $arrangement->course->teacher_form : '';
                                    if($j==$count){
                                        $dates = strtotime($model->start_time) + ($array[$index+$diff]['classday']-$startweek) * 60 * 60 * 24;
                                        $htime = floor($insert_array[$j]['end_time']/100)*3600+(int)substr($insert_array[$j]['end_time'],2)*60;
                                        $end_time=$dates+$htime;
                                    }
                                    $j++;
                                    $first_week_times++;
                                    $diff++;

                                }
                            }
                        }elseif($m>=$times_week){
                            if($count<$flag){//其他周并且还未将添加的剔除干净
                                array_pop($array);
                                $flag--;
                            }else{
                                $e = (int)$array[$j-1+$index]['start_time'];
                                $aaa=floor(($j-$first_week_times)%$times_week);
                                if($aaa==0){
                                    $time=strtotime($model->start_time)+ (floor(($j-$first_week_times)/$times_week) *7 +$array[$j-1+$index]['classday']-$startweek) * 60 * 60 * 24+ floor($e/100) * 60 * 60+(int)(substr($e,2))*60;
                                }else{
                                    $time=strtotime($model->start_time)+ (floor(($j-$first_week_times)/$times_week+1) *7 +$array[$j-1+$index]['classday']-$startweek) * 60 * 60 * 24+ floor($e/100) * 60 * 60+(int)(substr($e,2))*60;
                                }
                                if($j==$count){
                                    $end_time=$time;
                                }
                                $insert_array[$j]['class_id'] = $id;
                                $insert_array[$j]['class_date'] = $time;
                                $insert_array[$j]['start_time'] = $array[$j-1+$index]['start_time'];
                                $insert_array[$j]['end_time'] = $array[$j-1+$index]['end_time'];
                                $insert_array[$j]['lesson'] = $j;
                                $insert_array[$j]['title'] = isset($arrangement->course->name) ? $arrangement->course->name : '';
                                $insert_array[$j]['status'] = 0;
                                $insert_array[$j]['ovo'] = isset($arrangement->course->teacher_form) ? $arrangement->course->teacher_form : '';
                                $j++;
                            }
                        }
                    }
                    $model->start_time=$start_time;
                    $model->end_time=$end_time;
                    $model->save(false);
                        //批量插入class_lesson记录
                        Fun::getSiteDb()->createCommand()->batchInsert('{{%class_lesson}}', ['class_id', 'class_date', 'start_time', 'end_time', 'lesson', 'title', 'status', 'ovo'], $insert_array)->execute();

                        //批量修改class_student记录
                        Fun::getSiteDb()->createCommand()->update('{{%class_student}}', [ 'status' => 1, 'start_time' => $start_time, 'end_time' => $end_time], ['class_manage_id' => $id])->execute();
                        $class_student = ClassStudent::find()->where(['class_manage_id'=>$id])->all();
                        $student_check = [];
                        $lesson_students = [];
                        foreach ($class_student as $v) {
                            for ($i = 1; $i <= $count; $i++) {
                                $student_check[$i]['class_student_id'] = $v->id;
                                $student_check[$i]['order_sales_id'] = $v->order_sales_id;
                                $student_check[$i]['student_id'] = $v->student_id;
                                $student_check[$i]['status'] = 0;
                                $student_check[$i]['created_at'] = 0;
                                $class_lesson_id = ClassLesson::findOne(['class_id' => $id, 'lesson' => $i]);
                                $student_check[$i]['class_lesson_id'] = $class_lesson_id->lesson_id;

                                $lesson_students[$i]['lesson_id'] = $class_lesson_id->lesson_id;
                                $lesson_students[$i]['student_id'] = $v->student_id;
                                $lesson_students[$i]['status'] = 0;
                            }
                            Fun::getSiteDb()->createCommand()->batchInsert('{{%student_check}}', ['class_student_id', 'order_sales_id', 'student_id', 'status', 'created_at', 'class_lesson_id'], $student_check)->execute();
                            Fun::getSiteDb()->createCommand()->batchInsert('{{%lesson_student}}', ['lesson_id', 'student_id','status'], $lesson_students)->execute();
                        }
                        return $this->redirectMessage(\Yii::t('zhtfrontend', '开班成功'), Fun::url(['oldclassmanage/index']));
                    }

            } catch (\Exception $e) {
                $transaction->rollBack();
                return $this->redirectMessage(\Yii::t('zhtfrontend', '开班失败'), Fun::url(['oldclassmanage/index']));
            }
        }
        return $this->render('open', ['form' => $form->render(), 'model' => $model,'max_number'=>$max_number]);
    }

    /**
     * 删除
     */
    public function actionDelete()
    {
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $id = \Yii::$app->request->get('id');
        $class_manage = ClassManage::findOne(['class_id' => $id]);
        if ($class_manage == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        //判断该课程是否有学生
        $student = ClassStudent::find()->where(['class_manage_id'=>$id])->all();
        if(!empty($student) && $class_manage->status == 0){
            //若有学生且没开班 则不可以删除
            //throw new BadRequestHttpException(\Yii::t('zhtfrontend', '该课程已有学生预约或已开班，不能删除'));
            return $this->redirectMessage(\Yii::t('zhtfrontend', '该课程已有学生预约或已开班，不能删除'), Fun::url(['classmanage/index']));
        }else{
            //若没有学生且没开班 则可以删除
            //classmanage
            ClassManage::findOne([$id])->delete();
            //classlesson
            //ClassLesson::deleteAll(['class_id' => $id]);
            return $this->redirectMessage(\Yii::t('zhtfrontend', '删除成功'), Fun::url(['oldclassmanage/index']));
        }
    }

    /**
     * 老班添加学员
     */
    public function actionAddoldstudent()
    {
        $this->layout='@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $id = \Yii::$app->request->get('id');
        $model = ClassManage::findOne($id);
        $model->scenario = 'add';

        if (\Yii::$app->request->post('ajax') == 'createCard' && \Yii::$app->request->isAjax) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $cardnumber = Createcard::GenerateCard();
            return $cardnumber;
        }

        $form = new BuildForm('@app/components/forms/oldclassmanageForm.php');
        $form->loadModel(['classmanage' => $model]);
        $now_year = (int)date('Y');
        $oldyear = $now_year-60;
        $years = range($oldyear,$now_year);
        $arr = [];
        foreach($years as $y){
            $arr[$y] = $y;
        }
        $form->setItems('classmanage','age',$arr);
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'oldclassmanage-form' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return  ActiveForm::validate($model);
        }

        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $posts = \Yii::$app->request->post();
            $post = $posts['ClassManage'];
            $customerModel = Customer::find()->where(['mobile' => $post['telephone'],'site_id'=>Fun::getSiteId()])->one();
            if ($customerModel == null) {

                //添加到会员表
                $transaction = \Yii::$app->db->beginTransaction();
                try {
                    $customer = new Customer();
                    $customer->site_id = Fun::getSiteId();
                    $customer->name = $post['customer_name'];
                    $customer->mobile = $post['telephone'];
                    $customer->password = \Yii::$app->security->generatePasswordHash($post['password']);
                    $customer->created_at = time();
                    $customer->card_id = $post['card_id'];
                    $customer->card_qrcode = md5($post['card_id']);
                    $customer->sex = 'Female';
                    $customer->save(false);
                    $customer_id = $customer->id;

                    //添加到学生表
                    $student = new Student();
                    $student->customer_id = $customer_id;
                    $student->created_at = time();
                    $student->name = $post['student_name'];
                    $student->nickname = $post['student_name'];
                    $student->site_id = Fun::getSiteId();
                    $student->age = $post['age'];
                    $student->sex = $post['sex'];
                    $student->is_old = 1;
                    $student->save(false);
                    $student_id = $student->id;

                    //添加到class_student表
                    $class_student = new ClassStudent();
                    $class_student->class_manage_id = $id;
                    $class_student->student_id = $student_id;
                    $class_manage = ClassManage::find()->where(['class_id' => $id])->asArray()->one();
                    if (!empty($class_manage['start_time']) && $class_manage['status'] == 1) {
                        $class_student->status = 1;
                        $class_student->start_time = $class_manage['start_time'];
                        $class_student->end_time = $class_manage['end_time'];
                    }
                    $class_student->order_sales_id = $class_manage['associate_id'];
                    $class_student->save(false);

                    $class_student_id = $class_student->id;
                    //添加到student_check表
                    if ($class_manage['status'] == 1) {
                        $student_check = [];
                        $lesson_students = [];
                        $count = Arrangement::findone($class_manage['associate_id']);
                        for ($i = 1; $i <= (int)$count->class_count; $i++) {
                            $student_check[$i]['class_student_id'] = $class_student_id;
                            $student_check[$i]['order_sales_id'] = $class_manage['associate_id'];
                            $student_check[$i]['student_id'] = $student_id;
                            $student_check[$i]['status'] = null;
                            $student_check[$i]['created_at'] = null;
                            $class_lesson_id = ClassLesson::findOne(['class_id' => $id, 'lesson' => $i]);
                            $student_check[$i]['class_lesson_id'] = $class_lesson_id->lesson_id;

                            $lesson_students[$i]['lesson_id'] = $class_lesson_id->lesson_id;
                            $lesson_students[$i]['student_id'] = $student_id;
                            $lesson_students[$i]['status'] = 0;
                        }
                        Fun::getSiteDb()->createCommand()->batchInsert('{{%student_check}}', ['class_student_id', 'order_sales_id', 'student_id', 'status', 'created_at', 'class_lesson_id'], $student_check)->execute();
                        Fun::getSiteDb()->createCommand()->batchInsert('{{%lesson_student}}', ['lesson_id', 'student_id','status'], $lesson_students)->execute();
                    }
                    $transaction->commit();
                    return $this->redirectMessage(\Yii::t('zhtfrontend', '添加成功'), Fun::url(['oldclassmanage/index']));
                } catch (\Exception $e) {
                    $transaction->rollBack();
                    return $this->redirectMessage(\Yii::t('zhtfrontend', '添加失败'), Fun::url(['oldclassmanage/index']));
                }
            } else {
                $transaction = \Yii::$app->db->beginTransaction();
                try {
                    if(empty($customerModel->card_id)){
                        $customerModel->card_id =  $post['card_id'];
                        $customerModel->save(false);
                    }
                    $customer_id = $customerModel->id;
                   $student = Student::find()->where(['customer_id' => $customer_id])->one();
                    if ($student == null) {
                        $student = new Student();
                        $student->customer_id = $customer_id;
                        $student->created_at = time();
                        $student->name = $post['student_name'];
                        $student->nickname = $post['student_name'];
                        $student->site_id = Fun::getSiteId();
                        $student->age = $post['age'];
                        $student->sex = $post['sex'];
                        $student->is_old = 1;
                        $student->save(false);
                    } else {
                        $student->sex = $post['sex'];
                        $student->save(false);
                    }
                    //判断该学生是否已被添加到该班级
                    $in_class = ClassStudent::findone(['class_manage_id' => $id, 'student_id' => $student->id]);
                    $class_student = new ClassStudent();
                    if ($in_class == null) {
                        $class_student->class_manage_id = $id;
                        $class_student->student_id = $student->id;
                        $class_manage = ClassManage::find()->where(['class_id' => $id])->asArray()->one();
                        if (!empty($class_manage['start_time']) && $class_manage['status'] == 1) {
                            $class_student->status = 1;
                            $class_student->start_time = $class_manage['start_time'];
                            $class_student->end_time = $class_manage['end_time'];
                        }
                        $class_student->order_sales_id = $class_manage['associate_id'];
                        $class_student->save(false);
                        $class_student_id = $class_student->id;
                        if ($class_manage['status'] == 1) {
                            $student_check = [];
                            $lesson_students = [];
                            $count = Arrangement::findone($class_manage['associate_id']);
                            for ($i = 1; $i <= (int)$count->class_count; $i++) {
                                $student_check[$i]['class_student_id'] = $class_student_id;
                                $student_check[$i]['order_sales_id'] = $class_manage['associate_id'];
                                $student_check[$i]['student_id'] = $student->id;
                                $student_check[$i]['status'] = null;
                                $student_check[$i]['created_at'] = null;
                                $class_lesson_id = ClassLesson::findOne(['class_id' => $id, 'lesson' => $i]);
                                $student_check[$i]['class_lesson_id'] = $class_lesson_id->lesson_id;

                                $lesson_students[$i]['lesson_id'] = $class_lesson_id->lesson_id;
                                $lesson_students[$i]['student_id'] = $student->id;
                                $lesson_students[$i]['status'] = 0;
                            }
                            Fun::getSiteDb()->createCommand()->batchInsert('{{%student_check}}', ['class_student_id', 'order_sales_id', 'student_id', 'status', 'created_at', 'class_lesson_id'], $student_check)->execute();
                            Fun::getSiteDb()->createCommand()->batchInsert('{{%lesson_student}}', ['lesson_id', 'student_id','status'], $lesson_students)->execute();
                        }
                    }
                    $transaction->commit();
                    return $this->redirectMessage(\Yii::t('zhtfrontend', '该会员已存在'), Fun::url(['oldclassmanage/index']));
                } catch (\Exception $e) {
                    $transaction->rollBack();
                    return $this->redirectMessage(\Yii::t('zhtfrontend', '操作失败'), Fun::url(['oldclassmanage/index']));
                }
            }
        }
        return $this->render('addoldstudent',['form' => $form->render(), 'model' => $model]);
    }

    /**
     * 修改状态--class_lesson
     */
    public function actionStatus()
    {
        $this->layout='@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('lesson_id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $lesson_id = \Yii::$app->request->get('lesson_id');
        $model = ClassLesson::findOne([$lesson_id]);
        $form = new BuildForm('@app/components/forms/classlessonForm.php');
        $form->loadModel(['classmanage' => $model]);

        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $status = \Yii::$app->request->post();
            $classlesson = ClassLesson::findone([$lesson_id]);
            $classlesson->status = $status['ClassLesson']['status'];

            if($classlesson->save(false)){
                return $this->redirectMessage(\Yii::t('zhtfrontend', '添加成功'), Fun::url(['oldclassmanage/index']));
            }else{
                \Yii::$app->session->setFlash('error', '添加失败');
                return \Yii::$app->response->redirect(Fun::url(['oldclassmanage/index']));
            }

        }
        return $this->render('status',['form' => $form->render(), 'model' => $model]);
    }

    /**
     *  结束课程
     */
    public function actionEndcourse(){
        $id = \Yii::$app->request->get('id');
        if($id == null){
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $model = ClassManage::findOne($id);
        if(time() < $model->end_time){
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '请在最后一节课结束后结课'));
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try{
            $model->status = 2;
            $model->save(false);
            ClassStudent::updateAll(['status'=>2],'class_manage_id='.$id);
            $transaction->commit();
            return $this->redirectMessage(\Yii::t('zhtfrontend', '操作成功'), Fun::url(['classmanage/index']));
        }catch (\Exception $e){
            $transaction->rollBack();
            return $this->redirectMessage(\Yii::t('zhtfrontend', '操作失败'), Fun::url(['classmanage/index']));
        }
    }

    public function getClassLessonArray($length,$goods_time_array){
        $array=[];
        $ids_length=count($goods_time_array);
        for($i=0;$i<$length;$i++){
            if(empty($array)){
                $array[]=$goods_time_array[0];
            }else{
                $array[]=$goods_time_array[$i%$ids_length];
            }
        }
        return $array;
    }

}